package com.awesome.spring.controller;

import io.seata.saga.engine.StateMachineEngine;
import io.seata.saga.statelang.domain.ExecutionStatus;
import io.seata.saga.statelang.domain.StateMachineInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * OrderController
 *
 * @author alex wu
 * @date 2023/10/23
 */
@RequestMapping("/order")
@RestController
public class OrderController {

    @Autowired
    private StateMachineEngine stateMachineEngine;

    /**
     * http://localhost:9002/order/create?userId=101&money=10&count=1&rollback=false
     * @param userId
     * @param money
     * @param count
     * @param rollback
     * @return
     */
    @RequestMapping("/create")
    public String create(String userId, int money, int count, boolean rollback) {
        String orderCode = UUID.randomUUID().toString();
        Map<String, Object> startParams = new HashMap<>();
        startParams.put("orderCode", orderCode);
        startParams.put("userId", userId);
        startParams.put("money", money);
        startParams.put("count", count);
        startParams.put("rollback", rollback);

        String businessKey = String.valueOf(System.currentTimeMillis());
        StateMachineInstance stateMachineInstance = stateMachineEngine.startWithBusinessKey("order", null, businessKey, startParams);
        if (ExecutionStatus.SU.equals(stateMachineInstance.getStatus())) {
            return "下单成功";
        } else {
            return "下单失败";
        }
    }
}
